/*
 * @Author: jingfuu@163.com
 * @Date: 2024-11-08 13:44:32
 * @LastEditTime: 2024-12-07 21:04:26
 * @Description: 封装常用工具函数
 */
import { v4 as uuidv4 } from 'uuid';
import * as bcrypt from 'bcrypt';
import * as ExcelJS from 'exceljs';
import { ModuleRef } from '@nestjs/core';

export class Util {
  constructor(private moduleRef: ModuleRef) {}

  onModuleInit() {
    // const dictServiceInstance = this.moduleRef.get(DictService, {
    //   strict: false,
    // });
    // if (dictServiceInstance) {
    //   Util.dictService = dictServiceInstance;
    // }
  }

  static getUuid(): string {
    const uuidValue = uuidv4();
    return uuidValue;
  }

  static getCurrentLocalTime(): Date {
    const currentDate = new Date();
    currentDate.setHours(currentDate.getHours() + 8);
    return currentDate;
  }

  static getCurrentUTCTime() {
    return new Date();
  }

  static convertTimeStr(date: Date): string {
    if (date instanceof Date) {
      return Util.parseTime(Util.convertLocalTimeToUTC(date));
    } else {
      return date;
    }
  }

  static convertUTCToLocalTime(utcDate, timeZoneOffset = 8) {
    const offsetInMilliseconds = timeZoneOffset * 60 * 60 * 1000;
    return new Date(utcDate.getTime() + offsetInMilliseconds);
  }

  static convertLocalTimeToUTC(localDate, timeZoneOffset = 8) {
    const offsetInMilliseconds = timeZoneOffset * 60 * 60 * 1000;
    return new Date(localDate.getTime() - offsetInMilliseconds);
  }

  // 日期格式化
  static parseTime(time, pattern?) {
    if (arguments.length === 0 || !time) {
      return null;
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
      date = time;
    } else {
      if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
        time = parseInt(time);
      } else if (typeof time === 'string') {
        time = time
          .replace(new RegExp(/-/gm), '/')
          .replace('T', ' ')
          .replace(new RegExp(/\.[\d]{3}/gm), '');
      }
      if (typeof time === 'number' && time.toString().length === 10) {
        time = time * 1000;
      }
      date = new Date(time);
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay(),
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key];
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') {
        return ['日', '一', '二', '三', '四', '五', '六'][value];
      }
      if (result.length > 0 && value < 10) {
        value = '0' + value;
      }
      return value || 0;
    });
    return time_str;
  }

  static encryptPassword(password: string): string {
    return bcrypt.hashSync(password, 10);
  }

  static async excelExport(data: any[], header: any[]) {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Users');

    // 设置列头
    worksheet.columns = header;

    // 添加数据行
    worksheet.addRows(data);

    // 设置单元格样式
    const headerRow = worksheet.getRow(1);
    headerRow.eachCell({ includeEmpty: true }, (cell) => {
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: '808080' }, // 灰色背景
      };
      cell.font = { bold: true, color: { argb: 'FFFFFFFF' } }; // 白色字体
      cell.alignment = { horizontal: 'center', vertical: 'middle' }; // 文字居中
      cell.border = {
        top: { style: 'thin', color: { argb: '000000' } },
        left: { style: 'thin', color: { argb: '000000' } },
        bottom: { style: 'thin', color: { argb: '000000' } },
        right: { style: 'thin', color: { argb: '000000' } },
      }; // 黑色实线边框
    });

    // 设置数据行的单元格样式
    worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
      if (rowNumber > 1) {
        // 跳过表头
        row.eachCell({ includeEmpty: true }, (cell) => {
          cell.alignment = { horizontal: 'center', vertical: 'middle' }; // 文字居中
          cell.border = {
            top: { style: 'thin', color: { argb: '000000' } },
            left: { style: 'thin', color: { argb: '000000' } },
            bottom: { style: 'thin', color: { argb: '000000' } },
            right: { style: 'thin', color: { argb: '000000' } },
          }; // 黑色实线边框
        });
      }
    });

    // 将工作簿转换为Buffer
    const buffer = await workbook.xlsx.writeBuffer();
    return Buffer.from(buffer);
  }

  static async excelExportTemplate(header: any[]) {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Users');
    // 设置列头
    worksheet.columns = header;

    // 设置单元格样式
    const headerRow = worksheet.getRow(1);
    headerRow.eachCell({ includeEmpty: true }, (cell) => {
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: '808080' }, // 灰色背景
      };
      cell.font = { bold: true, color: { argb: 'FFFFFFFF' } }; // 白色字体
      cell.alignment = { horizontal: 'center', vertical: 'middle' }; // 文字居中
      cell.border = {
        top: { style: 'thin', color: { argb: '000000' } },
        left: { style: 'thin', color: { argb: '000000' } },
        bottom: { style: 'thin', color: { argb: '000000' } },
        right: { style: 'thin', color: { argb: '000000' } },
      }; // 黑色实线边框
    });
    // 将工作簿转换为Buffer
    const buffer = await workbook.xlsx.writeBuffer();
    return Buffer.from(buffer);
  }
}
